package actions;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import java.util.*;
import entities.*;

import javax.ejb.Local;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import utils.*;
import beans.*;

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 2L;

	@EJB
	private UserManagerLocal userManager = new UserManager();

	private String userName, passwd, message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public String execute() {
		// get user
		User u = userManager.getUser(userName, passwd);
		if (u == null) {
			message = "Login Unsuccessful. Your username or password is incorrect.";
			this.addActionError(message);
			return ERROR;
		} else {
			// add the session variable
			ActionContext.getContext().getSession().put("userId",
					new Integer(u.getUserId()));
			if (u.getUserType().equals("admin")) {
				ActionContext.getContext().getSession()
						.put("userType", "admin");
			} else {
				ActionContext.getContext().getSession().put("userType", "user");
			}
		}
		message = "Login Successful";
		return SUCCESS;
	}

}